package Thread_;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 *  Callable接口 带有返回值
 *   通过匿名内部类 ，重写它的 call方法完成任务
 *  通过 FutureTask类 将Thread与Callable连接
 */
public class Thread24 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Integer> callable = new Callable<Integer>(){
            @Override
            public Integer call() throws Exception {
                int sum=0;
                for(int i = 1; i <= 1000; i++ ){
                    sum +=i;
                }
                return sum;
            }
        };
//        Thread thread = new Thread(callable);
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println("sum= "+ futureTask.get());
    }
    //普通方法：
    private static int sum=0;//定义一个 静态成员变量
    public static void main2(String[] args) throws InterruptedException {
        Thread t=new Thread(()->{
            for(int i = 1;i <= 1000;i++){
                sum += i;
            }
        });
        t.start();
        t.join();//要等t线程执行结束
        System.out.println("sum= " + sum);
    }
    public static void main1(String[] args) throws ExecutionException, InterruptedException {
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i <= 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread t = new Thread(futureTask);
        t.start();
        System.out.println("count= "+futureTask.get());
    }
}
